# coding=utf-8
import os
import sys

base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "base.settings")

from common import orm

from common.lottery.cyclical.model import (
    ACTIVITY_MODEL, ORDER_MODEL, ORDER_LOGIC)
from common.lottery.cyclical import ORDER_STATUS
from common.transaction.db import create_transaction
from common.account.model.account import Account, BALANCE_TYPE
from common.utils.currency import convert_yuan_to_hao
from common.transaction.model import TRANSACTION_TYPE
from common.transaction.model import TRANSACTION_STATUS
from common.lottery.cyclical.abstract.order import WinOrderApplyer


def fix_error_open(activity_type, term, correct_number):
    """
    用于开错奖，追回彩金，重新开奖
    依然存在追号，数据统计,趋势图等问题
    :param activity_type:
    :param term:
    :param correct_number:
    :return:
    """
    assert activity_type
    assert term
    assert correct_number
    order_table = ORDER_MODEL[activity_type]
    orders = orm.session.query(order_table).filter(order_table.term == term).all()

    difference = []

    for order in orders:
        print("satrt fix order id {}".format(order.id))
        # 下分
        # 应该追回的钱

        should_amount = order.win_price + order.bonus
        if should_amount:

            account = Account.query.with_for_update().filter(Account.id == order.user_id).first()
            # 实际追回的钱
            real_amount = min(account.balance, should_amount)

            data = {
                'user_id': order.user_id,
                'type': TRANSACTION_TYPE.RECAPTURE,
                'title': u'款项追回',
                'price': -convert_yuan_to_hao(real_amount),
                'balance_type': BALANCE_TYPE.BALANCE,
                'status': TRANSACTION_STATUS.DONE
            }
            if real_amount:
                create_transaction(data)
            # 改变订单状态
            order.win_price = 0
            order.bonus = 0
            if real_amount != should_amount:
                difference.append(
                    u"user_id {}，show_amount{}，real_amount{}".format(order.user_id, should_amount, real_amount))

        order.status = ORDER_STATUS.READY
        order.save()

    # 修改正确的号码
    term_table = ACTIVITY_MODEL[activity_type]
    activity_term = orm.session.query(term_table).filter(term_table.term == term).first()
    if not activity_term:
        return
    activity_term.number = correct_number
    activity_term.save()

    # 重新开奖
    applyer = WinOrderApplyer(term, correct_number, ORDER_LOGIC[activity_type],
                              activity_type)

    applyer.apply()

    print(difference)


if __name__ == "__main__":
    activity_type = int(sys.argv[1])
    term = sys.argv[2]
    correct_number = sys.argv[3]
    print(u"start fix {} {} {}".format(activity_type, term, correct_number))
    fix_error_open(activity_type, term, correct_number)
    print(u'end fix')
